import pygame, hud, ResourceManager, GameObjectManager, EventHandler, Messages, Spawner
#from pygame.locals import *

class Game(object):

    POINTS_PER_KILL = 500
    POINTS_PER_TICK = 1

    FPS = 30
    
    def __init__(self, screen, rManager):
        self.screen = screen
        self.background = hud.Background(self.screen, (0,0), self.screen.get_size())
        
        
        self.gameObjectManager = GameObjectManager.GameObjectManager()
        self.gameObjectManager.linkAnimations(rManager, self.FPS)
        self.gameObjectManager.linkSounds(rManager)
        self.gameObjectManager.setSpawner(Spawner.KillBasedSpawner(self.gameObjectManager.addRandomKid, self.getKills))
        self.hud = hud.HUD(self.screen)
        self.clock = pygame.time.Clock()
        self.eventHandler = EventHandler.GameEventHandler(self, self.gameObjectManager)

        self.musicOn = False
        self.reset()
        
    def mainLoop(self):
        self.startMusic()
        while self.gameObjectManager.evilGreg.isAlive():
            if self.pause:
                self.pauseIt()
            self.clock.tick(self.FPS)
            self.eventHandler.doEvents(pygame.event.get())
            self.background.draw()
            self.gameObjectManager.update(self.screen)
            
            (health, hunger, self.kills)  = self.gameObjectManager.evilGreg.getStats()
            self.hud.update(self.kills, self.clock.get_fps(), health, hunger)
            self.hud.draw()
            
            self.timeScore += 1
            pygame.display.flip()                         
            

    def getKills(self):
        return self.kills

    def reset(self):
        self.gameObjectManager.reset()
        self.kills = 0
        self.timeScore = 0
        self.done = False
        self.pause = False
        
    def pauseIt(self):
        Messages.printPaused(self.screen)
        pygame.display.flip()
        musicPlaying = self.musicOn
        if musicPlaying:
            self.toggleMusic()
            
            EventHandler.waitForKeyOrQuit(self.eventHandler.PAUSE_KEY)
            self.pause = False
            
        if musicPlaying:
            self.toggleMusic()


    def getScore(self):
        return (self.timeScore * self.POINTS_PER_TICK) + (self.getKills() * self.POINTS_PER_KILL)


    def toggleMusic(self):
        self.musicOn = not self.musicOn
        if self.musicOn:
            pygame.mixer.music.unpause()
        else:
            pygame.mixer.music.pause()

    def startMusic(self):
        self.musicOn = True
        pygame.mixer.music.play(-1)
